jQuery(function($){

	//推送框隐藏
	$(".push-panel").hide();
	$(".copyright").hide();
	//记录页面上的微博数
	window.weibo_count=0;

	//判断是否有本地存储数据
	var sto=jQuery.parseJSON(window.localStorage.getItem("searchInfo"));
	if($.cookie("flowy_token") ){//若已登陆
		if(sto && $.cookie("flowy_token")==sto.flowy_token && sto.task){//存在本地数据
			var obj = new Weibo();

			for (var i=1; i<=sto.page; i++)
				obj.search_weibos("fresh",sto.key,sto.task,i,sto.weibos);
			//勾选已选择的微博
			$('.chooseNum').html(sto.weibos.length);
			for(var i=0; i<sto.weibos.length; i++){
				var li=$(".microblog-list li:eq("+sto.weibos[i].index+")");
				li.addClass("active");
				li.find(".microblog-panel-top input").attr("checked","checked");
			}
			//勾选已发送的微博
			if(sto.push_weibos.successful){
				for(var i=0; i<sto.push_weibos.successful.length; i++){
					var li=$(".microblog-list li:eq("+sto.push_weibos.successful[i].index+")");
					li.addClass("active").removeClass("available").addClass("unable");
					li.unbind("click");
					li.find(".microblog-panel-top input").replaceWith('<span class="send-succeed">已发送</span>');
				}
				for(var i=0; i<sto.push_weibos.failed.length; i++){
					var li=$(".microblog-list li:eq("+sto.push_weibos.failed[i].index+")");
					li.addClass("active").removeClass("available").addClass("unable");
					li.unbind("click");
					li.find(".microblog-panel-top input").replaceWith('<span class="send-failed">发送失败</span>');
				}
			}

			//推送显示
			$(".push-panel").show();
			if(sto.push_comment){
				$("#edit-txt").html(sto.push_comment);
				var regPattern = "(?:([A-Za-z]+):[/]{2})(?:[0-9A-Za-z-]+([.][0-9A-Za-z-]+)+)(?::([0-9]{1,5}))?(?:[/][/0-9A-Za-z_!~*\'().;?:@&=+$,%#-]*)?";
				var regex = new RegExp(regPattern, 'g');
				var value = sto.push_comment;
				var match_count = 0;
				if(value.match(regex) != null)
					match_count = value.match(regex).length;
				var num = 140 - value.replace(regex, "").length - 10 * match_count;
				// var num=140-sto.push_comment.length;
				if(num<0){
					$(".word-prompt").addClass("word-over").html('已超出<span id="rest-word">'+(-num)+'</span>个字');
				}
				else{
					$(".word-prompt").removeClass("word-over").html('还能再输入<span id="rest-word">'+num+'</span>个字')
				}
			}
		}
		else{
			$('#choosePage').hide();
		}
	}
	else{//未登陆
		$('#choosePage').hide();
	}


	//oops登陆
	$(".oops").click(function(e){
		$.ajax({
				url: "/admins/login",
				type: "GET",
				data: {
					'oops_id': "ttest~",
				},
				success: function(){
					$('BODY').f_popup({content:"登陆成功！",confirm:function(){$(".search input").focus();}});
				}
			})
		return false;
	});

	//搜索区
	$(".search-btn").click(function(e){
		e.stopPropagation();
		if(!$(this).hasClass("disabled")){
			var key=$('.search input').val();
			if(key==""||!key){
				$('BODY').f_popup({content:"请输入搜索内容！",confirm:function(){$(".search input").focus();}});
			}
			else if(!$.cookie("flowy_token")){
				$('.search input').blur();
				var html = '<span>您还没有登陆，请先选择门户网站登陆！</span><div class="lpanel"><ul><li>'+
				'<a class="sina" href="javascript:void(0)" title="新浪微博"></a></li>'+
				'<li><a class="qq" href="javascript:void(0)" title="腾讯微博"></a></li>'+
				'<li><a class="wy" href="javascript:void(0)" title="网易微博"></a></li>'+
				'<li><a class="oops" href="javascript:void(0)" title="OopsData"></a></li></ur></div>';
				var c = $('<div />').addClass("login-alert").html(html);
				$('BODY').f_popup({type:"login",content:c,size:{width:270},contentPosition:'center'});
			}
			else{
				$.waitState(true,"搜索中...",$(".search-btn"));
				$(".check-all input").removeClass("checked").prop("checked",false);
				var obj = new Weibo();
				$(".push-panel").hide();
				var sto=jQuery.parseJSON(window.localStorage.getItem("searchInfo"));
				obj.search_weibos("search",$('.search input').val(),null,1,null);
			}
		}
	});
	$(".search input").keypress(function(e){
		if( e.keyCode == 13 || e.keyCode == 27 )
			$(this).next().trigger('click');
	});

//高级搜索
	$(".screen").click(function(){
		$(window).scrollTo($('.screen'), 500);
	});
	$(".screen input:checkbox,.screen input:Radio").click(function(){
		$(".screen-r input").addClass("hover");
	});
	//日期
	$("#starttime").Zebra_DatePicker({offset:[-100,272],onSelect:function(){
			$(".screen-r input").addClass("hover");
			$("#starthour").removeClass("disabled");
		},onClear:function(){
			$("#starthour").find("span").attr("value","0").html("0");
			$("#starthour").addClass("disabled");
		},onChange:function(){
			$(window).scrollTo($('.screen'), 500);
	}});

	$("#endtime").Zebra_DatePicker({offset:[-100,272],onSelect:function(){
			$(".screen-r input").addClass("hover");
			$("#endhour").removeClass("disabled");
		},onClear:function(){
			$("#endhour").find("span").attr("value","23").html("23");
			$("#endhour").addClass("disabled");
		},onChange:function(){
			$(window).scrollTo($('.screen'), 500);
	}});
	//时间
	$(".time").ddl();
	//地区
	$("#province").next().areaSelect();
	//年龄
	$("input[name='age']").keyup(function(){  //keyup事件处理
		if(!isNaN($(this).val()))
			$(".screen-r input").addClass("hover");
        $(this).val($(this).val().replace(/\D|^0/g,''));
    }).bind("paste",function(){  //CTR+V事件处理
        $(this).val($(this).val().replace(/\D|^0/g,''));
        if(!isNaN($(this).val()))
			$(".screen-r input").addClass("hover");
    }).css("ime-mode", "disabled");  //CSS设置输入法不可用
    //筛选按钮
    $(".screen-r input").click(function(e){
		e.stopPropagation();
		if(!$(this).hasClass("disabled")){
			var sto=jQuery.parseJSON(window.localStorage.getItem("searchInfo"));
			if(!$.cookie("flowy_token")){
				$('.search input').blur();
				var html = '<span>您还没有登陆，请先选择门户网站登陆！</span><div class="lpanel"><ul><li>'+
				'<a class="sina" href="javascript:void(0)" title="新浪微博"></a></li>'+
				'<li><a class="qq" href="javascript:void(0)" title="腾讯微博"></a></li>'+
				'<li><a class="wy" href="javascript:void(0)" title="网易微博"></a></li>'+
				'<li><a class="oops" href="javascript:void(0)" title="OopsData"></a></li></ur></div>';
				var c = $('<div />').addClass("login-alert").html(html);
				$('BODY').f_popup({type:"login",content:c,size:{width:270},contentPosition:'center'});
			}
			else if(!$(this).hasClass("hover")) {
				$('BODY').f_popup({content:"请选择筛选条件！"});
			}
			else{
				$(this).removeClass("hover");
				$.waitState(true,"筛选中...",$(".screen-r input"));
				$(".check-all input").removeClass("checked").prop("checked",false);
				var obj = new Weibo();
				$(".push-panel").hide();
				var st="", et="",province="",city="";
				if($("#starttime").val()!="")
					st = $("#starttime").val()+"-"+$("#starthour").find("span").html();
				if($("#endtime").val()!="")
					et = $("#endtime").val()+"-"+$("#endhour").find("span").html();
				if($("#province").find("span").attr("value")!="1000"){
					province = $("#province").find("span").attr("value");
					city = $("#city").find("span").attr("value");
				}
				var screenData={stime:st,etime:et,pr:province,ci:city};
				obj.search_weibos("screen",sto.key,sto.task,1,null,screenData);
			}
		}

	});

	//选择区

	function choose(thisLi){
		var sto=jQuery.parseJSON(window.localStorage.getItem("searchInfo"));
		var weiboids=sto.weibos;
		var no=parseInt($(".chooseNum").html());
		if(!thisLi.hasClass("active")){
			thisLi.addClass("active");
			thisLi.find(".microblog-panel-top input").prop("checked", true);
			sto.weibos.push(thisLi.data("id"));
			//sto.weibos[sto.weibos.length]=thisLi.data("id");
			window.localStorage.setItem("searchInfo",JSON.stringify(sto));
			console.log(window.localStorage.getItem("searchInfo"));
			$(".chooseNum").html(no+1);
		}
		else{
			thisLi.removeClass("active");
			thisLi.find(".microblog-panel-top input").prop("checked", false);
			if($.searchInArray(thisLi.data("id").index,sto.weibos,"index")!=-1)
				sto.weibos.splice($.searchInArray(thisLi.data("id").index,sto.weibos,"index"),1);
			window.localStorage.setItem("searchInfo",JSON.stringify(sto));
			console.log(window.localStorage.getItem("searchInfo"));
			if(no>0) $(".chooseNum").html(no-1);
		}
	}
	$(".microblog-list").delegate("li.available","click",function(e){
		e.stopPropagation();
		choose($(this));
	});
	$(".microblog-list").delegate("li.available .username","click",function(e){
		e.stopPropagation();
		window.open('about:blank')
	});

	$(".check-all input").click(function(e){
		e.stopPropagation();
		if($(this).hasClass("checked")){//取消全选
			for(var i=0; i<$(".microblog-list li").length; i++){
				var thisLi = $(".microblog-list li:eq("+i+")");
				if(thisLi.hasClass("available")&&thisLi.hasClass("active"))
					choose(thisLi);
			}
			$(".check-all input").removeClass("checked").prop("checked",false);
		}
		else{
			$(".check-all input").addClass("checked").prop("checked",true);
			for(var i=0; i<$(".microblog-list li").length; i++){
				var thisLi = $(".microblog-list li:eq("+i+")");
				if(thisLi.hasClass("available")&&!thisLi.hasClass("active"))
					choose(thisLi);
			}
		}
	});

	$(".function-btn .more").click(function(e){
		e.stopPropagation();
		if(!$(this).hasClass("disabled")){
			var sto=jQuery.parseJSON(window.localStorage.getItem("searchInfo"));
			sto.page++;
			window.localStorage.setItem("searchInfo",JSON.stringify(sto));
			var obj = new Weibo();
			$.waitState(true,"加载中...",$(".more"));
			obj.search_weibos("more",sto.key,sto.task,sto.page,sto.weibos);
		}
	});

	$(".function-btn .finished").click(function(e){
		e.stopPropagation();
		//滑动到分享区
		$(".push-panel").show();
		$(window).scrollTo($('.push-panel'), 500);
	});

//分享区
	$(".push-btn").click(function(e){
		if(!$(this).hasClass("disabled")){
			e.stopPropagation();
			var key=$('#edit-txt').val();
			var no=parseInt($(".chooseNum").html());
			if(key==""||!key){
				$('BODY').f_popup({content:"请输入推送内容！",confirm:function(){$("#edit-txt").focus();}});
			}
			else if(no==0){
				$('BODY').f_popup({content:"您还未勾选微博！"});
			}
			else if($('.word-prompt').hasClass('word-over')){
				$('BODY').f_popup({content:"您输入的内容超出字数限制！",confirm:function(){$("#edit-txt").focus();}});
			}
			else{
				$.waitState(true,"发送中...",$(".push-btn"));
				var sto=jQuery.parseJSON(window.localStorage.getItem("searchInfo"));
				var obj = new Weibo();
				obj.comment_weibos(sto.task,sto.weibos,$("#edit-txt").val());
			}
		}
	});

	$("#edit-txt").bind("input propertychange",function(){
		//字数改变
		var regPattern = "(?:([A-Za-z]+):[/]{2})(?:[0-9A-Za-z-]+([.][0-9A-Za-z-]+)+)(?::([0-9]{1,5}))?(?:[/][/0-9A-Za-z_!~*\'().;?:@&=+$,%#-]*)?";
		var regex = new RegExp(regPattern, 'g');
		var value = $(this).val();
		var match_count = 0;
		if(value.match(regex) != null)
			match_count = value.match(regex).length;
		var num = 140 - value.replace(regex, "").length - 10 * match_count;

		// var num=140-$(this).val().length;

		if(num<0){
			$(".word-prompt").addClass("word-over").html('已超出<span id="rest-word">'+(-num)+'</span>个字');
		}
		else{
			$(".word-prompt").removeClass("word-over").html('还能再输入<span id="rest-word">'+num+'</span>个字')
		}

		//保存comment至本地存储中
		var sto=jQuery.parseJSON(window.localStorage.getItem("searchInfo"));
		sto.push_comment=$(this).val();
		window.localStorage.setItem("searchInfo",JSON.stringify(sto));
	});

	//nav
	$(".nav .rightSearch").click(function(e){
		e.stopPropagation();
		if(!$(this).hasClass("now")){
			$(window).scrollTo($('.logo'), 500);
		}
	});

	$(".nav .rightChoose").click(function(e){
		e.stopPropagation();
		if(!window.bindS&&!$(this).hasClass("now")){
			$(window).scrollTo($('.screen'), 500);
		}
	});

	$(".nav .rightShare").click(function(e){
		e.stopPropagation();
		//滑动到分享区
		if(!window.bindS&&!$(this).hasClass("now")){
			$(".push-panel").show();
			$(window).scrollTo($('.push-panel'), 500);
		}
	});

	$(".engine-toggle").click(function(e){
		$(".eng-list").fadeToggle(30);
	});
	$(".t-label").click(function(e){
		$(".eng-list").fadeOut(30);
		_this = $(this);
		$(".engine-toggle").attr('data',_this.attr('data'))
		$(".engine-toggle").html(_this.html().toString() + '<i class="triangle"></i>');
	});
});